<template>
  <section class="user">
    <div class="container">
      <div class="userBox">
        <TableRoleList :list="list" :column="column">
          <div slot="option" class="noBlueBg">
            <el-form :inline="true" :model="options" class="bottom-border" ref="optionForm">
              <el-form-item label="角色名" prop="name">
                <el-input v-model="options.name" clearable placeholder="请输入角色名" size="mini"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="mini" @click="loadList"><span class="el-icon el-icon-search"></span> 查询
                </el-button>
                <el-button size="mini" @click="resetOption('optionForm')"><span
                  class="el-icon el-icon-refresh-left"></span> 重置
                </el-button>
              </el-form-item>
              <el-form-item class="floatRight">
                <el-button size="mini" type="success" @click="add"><span class="el-icon el-icon-plus"></span>新增
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="page noBlueBg" slot="bottom">
            <el-pagination
              @size-change="changeSize"
              @current-change="changePage"
              :page-sizes="[20, 50, 100, 200]"
              :current-page="page"
              :page-size="limit"
              layout="sizes,total,prev, pager, next, jumper"
              :total="totals">
            </el-pagination>
          </div>
        </TableRoleList>
      </div>
      <Dialog :cfg="dialogCfg" ref="dialog">
        <el-form :model="editUser" label-width="80px" :inline="true" :rules="rules" ref="addForm">
          <el-form-item label="角色名" prop="name">
            <el-input v-model="editUser.name" clearable placeholder="请输入角色名" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="身份标签" prop="identityId">
            <el-select v-model="editUser.identityId" placeholder="请选择身份" size="mini">
              <el-option :label="label" :value="id" v-for="(label,id) in dict['identity']" :key="id" ></el-option>
            </el-select>
            <!-- <el-select v-model="editUser.code" placeholder="请选择身份" size="mini" @change="changeID">
              <el-option :label="label" :value="id" v-for="(label,id) in dict['identity']" :key="id" ></el-option>
            </el-select> -->
          </el-form-item>
          <el-form-item label="数据分组" prop="deptId">
            <el-select v-model="editUser.deptId" placeholder="请选择分组" size="mini" clearable>
              <el-option :label="item.label" :value="item.value+''" v-for="item in departmentOptions"
                         :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="页面权限" prop="menus">
            <el-select v-model="editUser.menus" placeholder="请选择页面" size="mini" @change="changeID">
              <el-option :label="label" :value="id" v-for="(label,id) in dict['identity']" :key="id" ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="页面权限" prop="menus">
            <el-cascader v-model="editUser.menus" :options="ymqx" :props="props" :show-all-levels="false" size="mini" @change="changeMenu" collapse-tags clearable></el-cascader>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editUser.remark" clearable placeholder="请输入备注" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="是否启用" prop="groups" class="mbn">
            <el-switch
              v-model="editUser.status"
              active-color="#03AAD3"
              inactive-color="#ccc">
            </el-switch>
          </el-form-item>
        </el-form>
      </Dialog>
    </div>
  </section>
</template>

<script>

  import TableRoleList from 'comp/common/TableRoleList';
  import Dialog from 'comp/common/Dialog.vue';


  export default {
    name: "Role",
    components: {
      Dialog,
      TableRoleList
    },
    data() {
      var Mobile = (rule, value, callback) => {
        const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        if (!value) {
          return callback(new Error("请输入手机号码！"));
        }
        if (!regMobile.test(value)) {
          return callback(new Error("手机号码格式错误！"));
        }
        callback();
      };
      return {
        nav: 'user',

        unitName: this.$kkui.cache.get('unit'),
        dict: this.$kkui.cache.get('dict'),
        orgData: [[], []],
        departmentOptions: [],
        departmentOptions2: [],
        preIdentityId:'',

        tabHeight: 0,
        options: {
          name: '',
        },
        props: { 
          multiple: true,
          emitPath:false,
          checkStrictly: true
         },
        ymqx:[],
        list: [],
        limit: 20,
        page: 1,
        pages: 1,
        totals: 0,

        column: [
          {
            prop: 'name',
            label: '角色名'
          },
          {
            prop: 'identityName',
            label: '身份标签'
          },
          {
            prop: 'department',
            label: '数据分组'
          },
          {
            prop: 'remark',
            label: '备注'
          },
          {
            prop: 'status',
            label: '状态',
            btn: 'switch'
          },
          {
            prop: '',
            label: '操作',
            btn: 'editAndDel',
            del: (id) => {
              this.del(id)
            },
            edit: (data) => {
              this.edit(data)
            }
          }
        ],
        dialogCfg: {},
        editUser: {
          name: '',
          identityId:'',
          deptId: '',
          remark: '',
          menus:'',
          status: true
        },
        rules: {
          // username: [
          //   {required: true, message: '请输入角色名', trigger: 'blur'}
          // ], 
          // realName: [
          //   {required: true, message: '请输入姓名', trigger: 'blur'}
          // ],
          // password: [
          //   {required: true, message: '请输入密码', trigger: 'blur'}
          // ],
          // mobile: [
          //   {required: true, validator: Mobile, trigger: "blur" }
          // ],
          // identityId: [
          //   {required: true, message: '请选择身份', trigger: 'change'}
          // ],
        }
      }
    },
    mounted() {
      this.loadList();
      this.getDepartments();
      this.loadMenuList();
    },
    methods: {
      getDepartments() {
        this.$server('role.getGroupList').then(data => {
          this.departmentOptions = data;
          // console.log(data);
          // this.unitName = this.$kkui.cache.get('unit');
          // let orgData = [[], []];
          // data.forEach(item => {
          //   if (item.name === '各分中心') {
          //     orgData[0] = item.children;
          //     this.departmentOptions = item.children;
          //   } else {
          //     item.children.forEach(itm => {
          //       orgData[1].push({...itm})
          //     })
          //   }
          // });
          // this.orgData = orgData;
        })
      },

      changeMenu(val){
        console.log(val);
      },

      //加载菜单列表
      loadMenuList() {
        this.$server('menu.list', {

        }).then(data => {
          this.ymqx = data;
          // console.log(data);
        })
      },

      //加载列表
      loadList() {
        this.$server('role.list', {
          limit: this.limit,
          page: this.page,
          ...this.options
        }).then(data => {
          // console.log(data);
          this.list = data['rows'].map(item => {
            return {
              ...item,
              status: item['status'] === '1',
            }
          });
          this.totals = data['total'];
          this.$kkui.loading_deepBlue.hide();
        })
      },

      //新增角色
      add() {
        this.editUser = {
          name: '',
          identityId:'',
          deptId: '',
          remark: '',
          menus:'',
          status: true
        },
        this.dialogCfg = {
          title: '新增角色',
          closeShow: true,
          footerShow: true,
          width: 615,
          height: 345,
          bg: true,
          submit: (callback) => {
            
            this.$refs['addForm'].validate((valid) => {
              if (valid) {
                // console.log(this.editUser)
                this.editUser.menus = this.editUser.menus.join(',');
                this.$server('role.add', {
                  ...this.editUser,
                  status: this.editUser.status ? '1' : '0'
                }).then(data => {
                  this.$kkui.msg({
                    icon: 1,
                    cont: '新增成功！'
                  });
                  this.loadList();
                  this.initEditData();
                  typeof callback === 'function' && callback();
                });
              } else {
                return false;
              }
            });
          }
        };
        this.$refs.dialog.show = true;
      },

      //编辑角色
      edit(data) {
        this.editUser = {password:'******',...data};
        this.editUser.menus = this.editUser.menus.split(",");
        // console.log(this.editUser.menus);

        this.dialogCfg = {
          title: '编辑角色',
          closeShow: true,
          footerShow: true,
          width: 615,
          height: 430,
          bg: true,
          submit: (callback) => {
            // console.log(1);
            this.$refs['addForm'].validate((valid) => {
              if (valid) {
                this.editUser.menus = this.editUser.menus.join(',');
                // console.log(this.editUser.menus);
                this.$server('role.edit', {
                  ...this.editUser,
                  status: this.editUser.status ? '1' : '0'
                }).then(data => {
                  this.$kkui.msg({
                    icon: 1,
                    cont: '保存成功！'
                  });
                  this.loadList();
                  this.initEditData();
                  typeof callback === 'function' && callback();
                });
              } else {
                return false;
              }
            });
          }
        };
        this.$refs.dialog.show = true;
      },

      //删除角色
      del(id) {
        this.$kkui.alert({
          icon: 0,
          cont: '确定删除此角色吗？',
          callback: () => {
            this.$server('role.delete', [id * 1]).then(data => {
              this.$kkui.msg({
                icon: '1',
                cont: '删除成功！'
              });
              this.loadList();
            })
          }
        });
      },

      initEditData() {
        this.editUser = {
          name: '',
          identityId:'',
          deptId: '',
          remark: '',
          menus:'',
          status: true
        };
      },

      //切换分页
      changePage(page) {
        this.page = page;
        this.loadList();
      },

      changeSize(limit) {
        this.limit = limit;
        this.loadList();
      },

      // 重置option
      resetOption(formName) {
        this.options= {
          name: '',

        };
        this.$refs[formName].resetFields();
        this.loadList();
      },
    }
  }
</script>

<style scoped lang="scss">
  @import "~css/system.scss";
</style>
